package com.qiniuyun.backai.handler;

import com.qiniuyun.backai.service.QiniuAsrService;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;

public class AsrWebSocketHandler implements WebSocketHandler {

    private final Map<String, QiniuAsrService> sessionServices = new ConcurrentHashMap<>();
    // 记录每个会话上次推送文本的长度，用于去重
    private final Map<String, Integer> sessionLastLengths = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("WebSocket连接建立: " + session.getId());

        // 为每个会话创建一个ASR服务实例
        QiniuAsrService asrService = new QiniuAsrService();
        sessionServices.put(session.getId(), asrService);

        // 连接到七牛云ASR服务，并通过回调实时推送识别结果到前端（长度去重）
        asrService.connectToQiniuAsr(text -> {
            if (text == null || text.isEmpty()) {
                return;
            }
            if (!session.isOpen()) {
                return;
            }

            int currentLen = text.length();
            Integer prevLen = sessionLastLengths.get(session.getId());
            if (prevLen != null && prevLen == currentLen) {
                return;
            }

            sessionLastLengths.put(session.getId(), currentLen);
            try {
                System.out.println("推送识别结果: " + text);
                session.sendMessage(new TextMessage(text));
            } catch (IOException e) {
                System.err.println("发送识别结果失败: " + e.getMessage());
            }
        });
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        QiniuAsrService asrService = sessionServices.get(session.getId());
        if (asrService == null) {
            System.err.println("未找到对应的ASR服务实例");
            return;
        }

        if (message instanceof BinaryMessage) {
            // 处理音频数据
            BinaryMessage binaryMessage = (BinaryMessage) message;
            byte[] audioData = binaryMessage.getPayload().array();

            try {
                // 转发音频数据到七牛云ASR服务
                asrService.sendAudioChunk(audioData);
            } catch (Exception e) {
                System.err.println("发送音频数据失败: " + e.getMessage());
                session.sendMessage(new TextMessage("音频处理失败: " + e.getMessage()));
            }
        } else if (message instanceof TextMessage) {
            // 处理文本消息（如控制指令）
            TextMessage textMessage = (TextMessage) message;
            String payload = textMessage.getPayload();
            System.out.println("收到文本消息: " + payload);

            if ("stop".equals(payload)) {
                session.sendMessage(new TextMessage("停止语音识别"));
                asrService.closeConnection();
            }
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.err.println("WebSocket传输错误: " + exception.getMessage());
        cleanupSession(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        System.out.println("WebSocket连接关闭: " + session.getId() + ", 状态: " + closeStatus);
        cleanupSession(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    private void cleanupSession(WebSocketSession session) {
        QiniuAsrService asrService = sessionServices.remove(session.getId());
        if (asrService != null) {
            asrService.closeConnection();
        }
        sessionLastLengths.remove(session.getId());
    }
}